package com.example.f8399.testdemo.utils.retrofit;

import java.io.IOException;
import java.net.Proxy;

import io.reactivex.plugins.RxJavaPlugins;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

/**
 * Created by f8399 on 2018/9/15.
 */

public class ServiceGenerator {
    private static  String BASE_URL = AppApi.BASE_URL;

    private static Retrofit.Builder builder = null;


    private static Retrofit retrofit;

    public static <T> T createService(Class<T> tClass) {

//        OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
        //****改进过后的builder  start
        OkHttpClient build = RetrofitUrlManager.getInstance().with(new OkHttpClient.Builder()).proxy(Proxy.NO_PROXY).build();
        OkHttpClient.Builder okHttpBuilder = build.newBuilder();
        //****改进过后的builder  end
        okHttpBuilder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
//                Request.Builder newRequest = request.newBuilder().addHeader("authorization", "secret-key");
                Request.Builder newRequest = request.newBuilder();
                return chain.proceed(newRequest.build());
            }
        });
        ServiceGenerator.builder = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpBuilder.build())
                .addConverterFactory(FastJsonConverterFactory.create())//使用fastjson
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create());//使用rxjava

        //.addConverterFactory(GsonConverterFactory.create())//使用Gson


        retrofit = ServiceGenerator.builder.build();

        return retrofit.create(tClass);
    }
}
